package com.rui.shangXueTang.huffman;

import java.util.*;

/**
 * @author : [锐神NO.3]
 * @version : [v1.0]
 * @className : HuffmanCodes
 * @createTime : [2022/2/18 14:21]
 * @description : [描述该类的功能]
 */

@SuppressWarnings("all")
public class HuffmanCodes {

    //1.统计字母锁出现的次数
    //2.获取到创建赫夫曼树
    //3.获取赫夫曼编码
    //4.数据压缩

    private static Map<Byte, String> huffmanCode = new HashMap<>();

    private static StringBuilder stringBuilder = new StringBuilder();

    public static void main(String[] args) {
        String string = "han guo qing, what's your name";
        byte[] bytes = string.getBytes();

        List<NodeCode> nodeWeight = getNodeWeight(string.getBytes());

        NodeCode root = createHuffmanTree(nodeWeight);

        Map<Byte, String> huffmanCodes = createHuffmanCodes(root);

        System.out.println("生成的赫夫曼编号 " + huffmanCodes);

        byte[] zip = zip(bytes, huffmanCodes);
        System.out.println("压缩后的数组: " + Arrays.toString(zip));

        //计算数据的压缩率
        float p = ((float)bytes.length - (float)zip.length) / (float)bytes.length;
        System.out.println(p);

        System.out.println("--------------------");

        byte[] decode = decode(huffmanCode, zip);
        System.out.println(new String(decode));
    }

    /**
     * 统计字符串所出现的次数
     */
    public static List<NodeCode> getNodeWeight(byte[] bytes){
        List<NodeCode> nodeCodes = new ArrayList<>();
        //每一个byte出现的次数，使用一个map集合 key value
        Map<Byte, Integer> counts = new HashMap<>();
        for(Byte b : bytes){
            Integer count = counts.get(b);
            if(count == null){
                counts.put(b, 1);
            }else {
                counts.put(b, count+1);
            }
        }

        for(Map.Entry<Byte, Integer> entry : counts.entrySet()){
            nodeCodes.add(new NodeCode(entry.getKey(), entry.getValue()));
        }
        return nodeCodes;
    }

    /**
     * 创建赫夫曼树
     */
    public static NodeCode createHuffmanTree(List<NodeCode> nodeCodes){
        //循环处理
        while(nodeCodes.size() > 1){
            //排序  从小到大排序
            Collections.sort(nodeCodes);

            //找到最小的两个元素
            NodeCode leftNode = nodeCodes.get(0);
            NodeCode rightNode = nodeCodes.get(1);

            //两个最小节点的权值,相加,生成新的节点
            NodeCode root = new NodeCode(leftNode.weight + rightNode.weight);

            //将新的节点作为父节点,构成一个新的二叉树
            root.left = leftNode;
            root.right = rightNode;

            nodeCodes.remove(leftNode);
            nodeCodes.remove(rightNode);

            nodeCodes.add(root);
        }
        return nodeCodes.get(0);
    }

    /**
     * 获取赫夫曼编码
     */
    public static void getHuffmanCode(NodeCode root, String code, StringBuilder stringBuilder){
        StringBuilder newString = new StringBuilder(stringBuilder);
        newString.append(code);
        if(root != null){
            if(root.data == null){
                //向左递归
                getHuffmanCode(root.left, "0", newString);

                //向右递归
                getHuffmanCode(root.right, "1", newString);
            }else {
                huffmanCode.put(root.data, newString.toString());
            }
        }
    }

    /**
     * 统一的入口
     */
    public static Map<Byte, String> createHuffmanCodes(NodeCode root){
        if(root == null){
            return null;
        }else {
            //处理左子树
            getHuffmanCode(root.left, "0", stringBuilder);

            //处理右子树
            getHuffmanCode(root.right, "1", stringBuilder);

            return huffmanCode;
        }
    }

    /**
     * 数组压缩,把赫夫曼编码转换成十进制数据
     */
    public static byte[] zip(byte[] bytes, Map<Byte, String> huffmanCode){
        //用来拼接所有叶子节点的所有路径
        StringBuilder stringBuilder = new StringBuilder();
        for(byte b : bytes){
            stringBuilder.append(huffmanCode.get(b));
        }

        int length = stringBuilder.length() % 8 == 0 ? stringBuilder.length() / 8 : stringBuilder.length() / 8 + 1;

        //压缩数据的数组
        byte[] huffmanCodeBytes = new byte[length];

        int index = 0;

        for(int i = 0 ; i < stringBuilder.length() ; i += 8){
            String str;
            if(i + 8 > stringBuilder.length()){
                str = stringBuilder.substring(i);
            }else {
                str = stringBuilder.substring(i, i+8);
            }
            huffmanCodeBytes[index] = (byte) Integer.parseInt(str, 2);
            index++;
        }
        return huffmanCodeBytes;
    }

    /**
     * 数据的解压缩过程
     */
    public static String byteToString(boolean isRepair, byte b){
        int temp = b;
        if(isRepair){
            temp |= 256;
        }

        String string = Integer.toBinaryString(temp);
        if(isRepair){
            return string.substring(string.length() - 8);
        }else {
            return string;
        }
    }

    public static byte[] decode(Map<Byte, String> huffmanCode, byte[] huffmanBytes){
        StringBuilder stringBuilder = new StringBuilder();
        for(int i = 0 ; i < huffmanBytes.length ; i++){
            byte b = huffmanBytes[i];
            boolean flag = false;
            if(i == huffmanBytes.length - 1){
                flag = true;
            }
            stringBuilder.append(byteToString(!flag, b));
        }
        Map<String, Byte> map = new HashMap<>();
        for(Map.Entry<Byte, String> entry : huffmanCode.entrySet()){
            map.put(entry.getValue(), entry.getKey());
        }

        List<Byte> bytes = new ArrayList<>();

        for(int i = 0 ;  i < stringBuilder.length();){
            int count = i;
            boolean flag = true;
            Byte b = null;
            while(flag){
                String key = stringBuilder.substring(i, i + count);
                b = map.get(key);
                if(b == null){
                    count++;
                }else {
                    flag = false;
                }
            }
            bytes.add(b);
            i += count;
        }

        byte[] buff = new byte[bytes.size()];
        for (int i = 0; i < buff.length; i++) {
            buff[i] = bytes.get(i);
        }
        return buff;
    }
}
